#include "gwbase/base/daemon.h"

#include <unistd.h>
#include <stdio.h>
#include "gwbase/base/logging.h"

namespace dicom {

int Daemon::Run(void* arg) {
  int p = fork();

  if (p < 0) {
    LOG_FATAL << "faild to fork";
  }

  // parent process
  if (p > 0) {
    ::exit(EXIT_SUCCESS);
  }

  // child to session leader
  if (setsid() < 0) {
    LOG_FATAL << "faild to setsid";
  }

  // fork again, so we are not session leader
  p = fork();
  if (p < 0) {
    LOG_FATAL << "faild to fork";
  }

  // parent process
  if (p > 0) {
    ::exit(EXIT_SUCCESS);
  }

  return main_(arg);
}
};
